package com.somsoft.unlockme;

import android.graphics.Canvas;
import android.os.Looper;
import android.view.SurfaceHolder;

import com.somsoft.unlockme.fk.C;

/**
 * 该类继承自Thread，主要负责定时刷新JiyiliView
 */
public class UnlockMeDrawThread extends Thread {
	UnlockMeView view; // WelcomeView对象的引用
	SurfaceHolder surfaceHolder; // WelcomeView对象的SurfaceHolder
	int sleepSpan = 100; // 休眠时间
	boolean flag; // 线程执行标志位

	// 构造器：初始化主要的成员变量
	public UnlockMeDrawThread(UnlockMeView view, SurfaceHolder surfaceHolder) {
		this.view = view;
		this.surfaceHolder = surfaceHolder;
		this.flag = true;
	}

	// 方法：线程执行方法
	public void run() {
		Looper.prepare();
		Canvas canvas = null; // 创建一个Canvas对象
		while (flag) {
			try {
				canvas = surfaceHolder.lockCanvas(null); // 为画布加锁
				synchronized (surfaceHolder) {
					view.doDraw(canvas); // 重新绘制屏幕
					if(view.isPass){
						view.isPass = false;
						view.activity.myHandler.sendEmptyMessage(0);
					}
					if("select".equals(C.clickedBtn)){
						view.activity.myHandler.sendEmptyMessage(1);
					}else if("reload".equals(C.clickedBtn)){
						view.activity.myHandler.sendEmptyMessage(2);
					}else if("next".equals(C.clickedBtn)){
						view.activity.myHandler.sendEmptyMessage(3);
					}else if("jump".equals(C.clickedBtn)){
						view.activity.myHandler.sendEmptyMessage(4);
					}
					C.clickedBtn = "";
				}
			} catch (Exception e) {
				e.printStackTrace(); // 捕获异常并打印
			} finally {
				if (canvas != null) {// 释放画布并将其传回
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
			try {
				Thread.sleep(sleepSpan); // 休眠一段时间
			} catch (Exception e) {
				e.printStackTrace(); // 捕获异常并打印
			}
		}
	}
}